﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Text;

namespace MicroMq.Core
{
    public class MicroMqOptions
    {
        public string Url { get; set; } = "mtp://micro@192.168.0.1:9999";

        private string Cipher = "micro";

        private int Port = 9999;

        private string Ip;

        private void Param(string arg)
        {
            var dict = arg.Split("&").Select(a => a.Split('='))
                  .ToDictionary(a => a[0], a => a[1]);
        }


        private bool Init()
        {
            if (Url == null || Ip != null) return Ip != null;
            var url = Url.Replace("mtp://", "");
            if (url.Contains("?"))
            {
                var arr = url.Split("?");
                url = arr[0];
                Param(arr[1]);
            }
            if (url.Contains("@"))
            {
                var arr = url.Split("@");
                Cipher = arr[0];
                url = arr[1];
            }
            if (url.Contains(":"))
            {
                var arr = url.Split(":");
                url = arr[0];
                if (!int.TryParse(arr[1], out Port))
                {
                    Port = 999;
                }
            }
            Ip = url;
            return true;
        }

        public EndPoint GetEndPoint()
        {
            if (!Init())
                throw new ArgumentException("参数初始化错误");
            return new IPEndPoint(IPAddress.Parse(Ip), Port);
        }

        public string GetCipher()
        {
            if (!Init())
                throw new ArgumentException("参数初始化错误");
            return Cipher;
        }
    }
}
